package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.question.domain.ListenRecord;
import com.wuwei.elearning.question.mapper.ListenRecordMapper;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-06-16
 */
@RestController
@RequestMapping("/elearning/listenRecord")
public class ListenRecordController {

    @Resource
    private ListenRecordMapper listenRecordMapper;

    @PostMapping("updateScore/{score}/{id}")
    public Result<String> updateScore(@PathVariable("score") Integer score, @PathVariable("id") Long audioId, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        LambdaQueryWrapper<ListenRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ListenRecord::getAccount,account).eq(ListenRecord::getAudioId,audioId);
        ListenRecord listenRecord = listenRecordMapper.selectOne(queryWrapper);
        if (listenRecord==null) {
            listenRecord = new ListenRecord();
            listenRecord.setAccount(account);
            listenRecord.setAudioId(audioId);
            listenRecord.setScore(score);
            listenRecord.setTime(LocalDateTime.now());
            listenRecordMapper.insert(listenRecord);
        } else {
            Integer recordScore = listenRecord.getScore();
            //如果这次听力成绩比上次好，就记录下来，否则不记录
            if (score>recordScore) {
                listenRecord.setScore(score);
                listenRecord.setTime(LocalDateTime.now());
                listenRecordMapper.update(listenRecord,queryWrapper);
            }
        }
        return Result.ok("更新成功！");
    }
}

